package com.freshmarket.freshmarket.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.freshmarket.freshmarket.configuration.AlipayConfig;
import com.freshmarket.freshmarket.dao.UserMapper;
import com.freshmarket.freshmarket.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@Slf4j
public class CallBackController {
    @Resource
    private UserMapper userMapper;

    @RequestMapping("/payNotify")
    public void money(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";

            }
            //乱码解决，这段代码在出现乱码时使用
            //alueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //String id = request.getParameter("userId");
        //System.out.println();
        boolean signVerified;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
            if (signVerified) {//验证成功
                //商户订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
                String userId = new String(request.getParameter("subject").getBytes("ISO-8859-1"), "UTF-8");
                //支付宝交易号
                String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
                //交易状态
                String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
                String money = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
                if (trade_status.equals("TRADE_SUCCESS")) {
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //如果有做过处理，不执行商户的业务程序
                    //注意：
                    //付款完成后，支付宝系统发送该交易状态通知
                    System.out.println("商户订单号" + out_trade_no);
                    System.out.println("支付宝交易号" + trade_no);
                    System.out.println("交易金额" + money);
                    //当前时间
                    String tradeTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    System.out.println("交易时间" + tradeTime);
                    User user = userMapper.selectById(userId);

                    request.getSession().setAttribute("user", user);

                    //response.getWriter().println(new Result(true,200,"成功回调",user));
                    //更新用户金额
                    User user1 = new User();
                    System.out.println("用户Id" + userId);
                    user1.setUserId(Integer.parseInt(userId));
                    System.out.println("异步回调id" + Integer.parseInt(userId));
                    user1.setUserMoney(user.getUserMoney() + Double.parseDouble(money));
                    userMapper.updateById(user1);


                   /* User user = userMapper.selectById(Integer.parseInt(userId));
                    user.setUserBalance(user.getUserBalance().add(new BigDecimal(money)));
                    userService.updateBalance(user,money,out_trade_no);*/
                    //业务操作

                }

            }
        } catch (AlipayApiException | UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_idller_email）
	4、验证app_id是否为该商户本身。
	*/

    }
}
